package androidx.lifecycle

import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
import java.io.Closeable
import kotlin.coroutines.CoroutineContext

private const val KEY_IO_SCOPE = "androidx.lifecycle.ViewModelCoroutineScope.KEY_IO_SCOPE"

val ViewModel.ioScope: CoroutineScope
    get() {
        val scope: CoroutineScope? = this.getTag(KEY_IO_SCOPE)
        if (scope != null) {
            return scope
        }
        return setTagIfAbsent(
            KEY_IO_SCOPE,
            CloseableCoroutineIOScope(SupervisorJob() + Dispatchers.IO)
        )
    }

internal class CloseableCoroutineIOScope(context: CoroutineContext) : Closeable, CoroutineScope {
    override val coroutineContext: CoroutineContext = context

    override fun close() {
        coroutineContext.cancel()
    }
}
